<?php


$dir = dirname(__FILE__);

require_once("Communicator.php");
require_once("Database.php");
require_once("User.php");

class Room{
	private $id;
	private $group;

	private $db;
	private $cmm;
	private $session;

	public function __construct($id=null){
		if(session_id() == '') session_start();

		$this->id = $id;

		$this->db = new Database;
		$this->cmm = new Communicator;
	}

	public function setId($id){
		$this->id = $id;
	}

	public function getId(){
		return $this->id;
	}

	public function getGroup(){
		return $this->group;
	}

	public function setGroup($group=null){
		if(is_object($group)) $this->group = $group;
		else $this->group = $this->retrieveGroup($group);
	}

	public function getPath(){
		return "room/$this->id/";
	}

	public function getLogPath(){
		return "log/$this->id/";
	}

	public function open($groupId=null){
		if($groupId != null) $this->setGroup($groupId);

		$this->db->execute("SELECT id FROM room r WHERE r.group = '{$this->group->id}' AND end IS NULL");
		if($this->db->getNumberOfRows() == 0){
			$this->db->execute("INSERT INTO room (`group`, start) VALUES ('{$this->group->id}', NOW())");
		
			$this->id = $this->db->getInsertedId();

			$this->group->members = $this->retrieveMembers();

			$this->setUpFolder();
			$this->sendCreationNotification();

			return true;
		}else return false;
	}

	public function close(){
		$this->db->execute("UPDATE room SET end = NOW() WHERE id = {$this->id} AND end IS NULL");

		if($this->db->getAffectedRows() > 0){
			$res = $this->db->execute("SELECT session, user FROM session_update WHERE room = {$this->id}");
			$user = new User;
			$user->setRoom($this->id);

			while($update = mysql_fetch_array($res,MYSQL_ASSOC)){
				$user->setSession($update['session']);
				$user->setId($update['user']);
				$user->leaveRoom();
			}
			
			$this->saveLog();

			require_once 'php/FileHandler.php';
			$fh = new FileHandler;
			$fh->deleteDirectory("room/{$this->id}",false);

			echo 1;
		}
	}

	public function saveLog(){
		$logPath = "log/{$this->id}";

		$file = fopen($logPath, 'a+');
		fwrite($file, '{');

		$this->db->execute("SELECT user, time, type FROM access WHERE room = {$this->id}");
		$access = $this->db->toArray(MYSQL_NUM);
		fwrite($file, '"access":'.json_encode($access));
		
		$this->db->execute("SELECT m.id, m.user, m.text, m.time, m.parent FROM message m INNER JOIN session s ON m.session = s.id WHERE s.room = {$this->id}");
		$message = $this->db->toArray(MYSQL_NUM);
		fwrite($file, ',"message":'.json_encode($message));

		$group = file_get_contents("room/{$this->id}/group");
		fwrite($file,',"group":'.$group);
		
		fwrite($file, '}');
		fclose($file);

		$logContent = file_get_contents($logPath);

		$this->db->execute("INSERT INTO log (room, content) VALUES ({$this->id}, '$logContent')");
	}

	public function endAllSessions(){
		$query = "UPDATE session SET end = NOW() WHERE room = {$this->id}";

		$this->db->execute($query);
	}

	private function setUpFolder(){
		$path = $this->getPath();
		$group = array('id'=>$this->group->id, 'name'=>$this->group->name, 'members'=>$this->group->members);
		
		$fh = new FileHandler($path);

		$fh->createDirectory();
		//s$fh->createDirectory('user/'); //folder where the users will be placed
		
		//$fh->createFile('last_id',0); //create file with last message id
		//$fh->createFile('reply','{"parent":{},"children":{}}'); //create file with reply tree
		//$fh->createFile('message'); //create file with messages
		//$fh->createFile('login'); //create file with login
		$fh->createFile('group',json_encode($group)); //create file with information of the room's group
	}

	private function sendCreationNotification(){
		/*$members = $this->retrieveMembers();

		foreach($members as $member){
			$memberId = $member['id'];
			$this->cmm->sendNotification($memberId,'Uma sala foi criada no grupo '.$this->group->name);
		}*/

		require_once('Post.php');

		$params = array('room' => $this->id);
		
		$post = new Post($params);
		$post->send();
	}

	public function placeData(){
		global $dir;
		require_once('tools.php');
		$this->session = new Session();

		$this->db->execute("SELECT * FROM room WHERE id = $this->id");
		$array = $this->db->toArray(MYSQL_ASSOC);
		$data = $array[0];
		$groupId = $data['group'];

		$group = $this->cmm->getData($groupId, array('name','owner','members'=>array('name', 'username')));
		
		if($this->session->getData('id') == $group['owner']['id']) $this->session->setData('isOwner_'.$this->id);

		$members = $this->setMembersAttributes($group['members']['data']);
		unset($group['members']);
		$roomData['group'] = $group;

		$this->db->execute("SELECT user, status FROM session_update WHERE room = {$this->id}");
		$userStatus = $this->db->toArray(MYSQL_NUM);

		$response = array('roomData'=>$data, 'roomMembers'=>$members, 'userStatus'=>$userStatus);
		
		insertScriptTag($response);
	}

	private function retrieveGroup($groupId=null){
		if($groupId == null){
			if(is_numeric($this->group)) $groupId = $this->group;
			else $groupId = $this->retrieveGroupId();
		}
		
		$data = $this->cmm->getData($groupId, array('name','owner'));
		
		$group = new stdClass;

		foreach($data as $property => $value) $group->$property = $value;

		return $group;
	}


	private function retrieveGroupId(){
		$res = $this->db->execute("SELECT r.group FROM room r WHERE id = {$this->id}");
			
		$record = mysql_fetch_array($res, MYSQL_ASSOC);
		return $record['group'];
	}

	private function retrieveMembers($attributes = array('name', 'username')){
		if(!is_object($this->group)) $this->group = $this->retrieveGroup();

		$group = $this->cmm->getData($this->group->id, array('members'=>$attributes));

		return $group['members']['data'];
	}

	private function setMembersAttributes($members){
		$userId = $this->session->getData('id');
		$membersCopy = $members;
		
		//get all members who currently have a session opened
		$res = $this->db->execute("SELECT * FROM session WHERE room = {$this->id} AND end IS NULL");
		
		//check who's online and what is the target member
		while($session = mysql_fetch_array($res, MYSQL_ASSOC)){
			foreach($membersCopy as $key => $member){
				if($session['user'] == $member['id']){
					if($session['user'] == $userId){
						$members[$key]['isMe'] = 1; //check if it's the user, could be saved in database...
						$members[$key]['session'] = $this->session->getData('session_room_'.$this->id);
					} 
					
					$members[$key]['status'] = 0;
					
					unset($membersCopy[$key]);
					
					break;
				}
			}
		}

		foreach($membersCopy as $key => $member) $members[$key]['status'] = 0;

		return $members;
	}

	public function saveDatabaseLogInFile($room){
		$path = "log/$room";
		$res = $this->db->execute("SELECT content FROM log WHERE room = $room");

		$array = mysql_fetch_array($res, MYSQL_ASSOC);

		file_put_contents($path, $array['content']);
	}

}

?>